﻿using FreeRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Volo.Abp.Caching;
using Volo.Abp.Modularity;

namespace Framework.Caching.FreeRedis
{
	/// <summary>
	/// 缓存管理 模块，此模块得益于FreeRedis作者支持IDistributedCache，使用湿滑
	/// </summary>
	[DependsOn(typeof(AbpCachingModule))]   // 集成 缓存管理功能 模块
	public class FrameworkCachingFreeRedisModule : AbpModule
	{
		public override void ConfigureServices(ServiceConfigurationContext context)
		{
			var configuration = context.Services.GetConfiguration();

			//注入缓存类
			context.Services.AddSingleton(typeof(IWantDistributedCache), typeof(WantDistributedCache));

			var redisEnabled = configuration["Redis:IsEnabled"];							// 读取Redis是否启用配置
			if (!redisEnabled.IsNullOrEmpty() && bool.Parse(redisEnabled))
			{   // 启用Redis才继续
				
				var redisConfiguration = 
					new ConnectionStringBuilder[] { configuration["Redis:Configuration"] };		// 读取Redis连接配置

				RedisClient redisClient = new RedisClient(redisConfiguration);	// 初始化Redis客户端

				context.Services.AddSingleton<IRedisClient>(redisClient);			// 注入Redis客户端类
				context.Services.Replace(ServiceDescriptor.Singleton<IDistributedCache>(new
					 DistributedCache(redisClient)));												// 替换为使用Redis缓存
			}

			
			Configure<AbpDistributedCacheOptions>(cacheOptions =>
			{
				//cacheOptions.GlobalCacheEntryOptions.SlidingExpiration = null;  //设置缓存不要过期，默认滑动20分钟
																				
				cacheOptions.KeyPrefix = "MYGPS:";                              //缓存key前缀
			});
		}
	}
}
